<template>
  <div class="login">
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.phone"
        name="手机号"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          { validator: checkPhone, message: '手机号码有误' }
        ]"
      />
      <van-field
        v-model="form.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^[0-9a-zA-Z]{6,12}$/, message: '请填写6~12位密码' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="isLoading"
          round
          block
          type="info"
          native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { NavBar, Button, Field, Form, Toast } from 'vant'
import { login } from '@/service/user'
export default {
  name: 'Login',
  components: {
    VanNavBar: NavBar,
    VanButton: Button,
    VanForm: Form,
    VanField: Field
  },
  data () {
    return {
      // 登录状态
      isLoading: false,
      form: {
        phone: '',
        password: ''
      }
    }
  },
  methods: {
    // 返回上一页面
    onClickLeft () {
      this.$router.go(-1)
    },
    // 登录
    async onSubmit () {
      // console.log('submit', values)
      this.isLoading = true
      const { data } = await login(this.form)
      if (data.state === 1) {
        Toast.success('登录成功')
        this.$store.commit('setUser', data.content)
        this.$router.push(this.$route.query.redirect || '/course')
      } else {
        Toast.error(data.message)
      }
      this.isLoading = false
    },
    // 检查手机号格式是否正确
    checkPhone (value) {
      return /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value)
    }
  }
}
</script>

<style></style>
